package com.hb.znpt.viewmodel;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.ObservableField;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.hb.znpt.activity.ScannerActivity;
import com.hb.znpt.bean.LeaseBean;
import com.hb.znpt.image.GlideEngine;
import com.hb.znpt.model.UserInfoModel;
import com.hb.znpt.utils.Constants;
import com.hb.znpt.utils.LogUtils;
import com.hb.znpt.utils.OssManager;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.rxjava.rxlife.RxLife;
import com.unitlib.base.base.BaseViewModel;
import com.unitlib.base.utils.SPUtils;
import com.unitlib.base.utils.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * @Description: 描述
 * @Author: houbing
 * @CreateDate: 2021/12/18 20:29
 */
public class UserInfoViewModel extends BaseViewModel<UserInfoModel> {

    public ObservableField<String> number = new ObservableField<>("");

    public MutableLiveData<String> bankData = new MutableLiveData<>();
    public MutableLiveData<String> cardData = new MutableLiveData<>();

    public String cardPath, cardUrl;
    public String bankPath, bankUrl;

    public boolean isCardUploaded = false, isBankUploaded = false;

    public UserInfoViewModel(@NonNull Application application) {
        super(application);
        model = new UserInfoModel();
    }

    @Override
    public void onCreate() {
        XXPermissions.with(context)
                .permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {

                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtils.showShort("被永久拒绝授权，请手动授权限");
                            XXPermissions.startPermissionActivity(context, permissions);
                        }
                    }
                });
        info();
    }

    public void info() {
        model.info()
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    getUC().getShowLoadingDialogEvent().call();
                })
                .doFinally(() -> {
                    getUC().getDismissLoadingDialogEvent().call();
                })
                .as(RxLife.as(owner))
                .subscribe(been -> {
                    number.set(been.getYhk());
                    if (!TextUtils.isEmpty(been.getSfzurl())) {
                        cardData.setValue(been.getSfzurl());
                    }
                    if (!TextUtils.isEmpty(been.getYhkurl())) {
                        bankData.setValue(been.getYhkurl());
                    }
                }, error -> {
                    ToastUtils.showShort(error.getMessage());
                });
    }

    public void bank(View view) {
        PictureSelector.create(activity)
                .openCamera(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .maxSelectNum(1)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                .isAndroidQTransform(true)// 是否需要处理Android Q 拷贝至应用沙盒的操作，只针对compress(false); && .isEnableCrop(false);有效,默认处理
                .isDisplayOriginalSize(true)// 是否显示原文件大小，isOriginalImageControl true有效
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                .isPreviewImage(true)// 是否可预览图片
                .isCamera(true)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .isEnableCrop(false)// 是否裁剪
                .isCompress(true)// 是否压缩
                .compressQuality(80)// 图片压缩后输出质量
                .isGif(false)// 是否显示gif图片
                .isCropDragSmoothToCenter(true)// 裁剪框拖动时图片自动跟随居中
                .minimumCompressSize(100)// 小于多少kb的图片不压缩
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        bankPath = result.get(0).getCompressPath();
                        bankData.setValue(result.get(0).getPath());
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    public void card(View view) {
        startActivityForResult(ScannerActivity.class, 10001);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == 10001) {
            Log.e(TAG, data.getStringExtra("data"));
            JSONObject jsonData = JSON.parseObject(data.getStringExtra("data"));
            Log.e(TAG, jsonData.getString("cardNumber"));
            if (jsonData.getString("cardNumber").equals(SPUtils.getInstance().getString(Constants.SP_USERCARD))) {
                cardPath = data.getStringExtra("path");
                cardData.setValue(data.getStringExtra("path"));
            } else {
                ToastUtils.showShort("身份证识别失败请重新扫描！");
            }
        }
    }

    public void submit(View view) {
        if (isEmpty()) {
            getUC().getShowLoadingDialogEvent().call();
            uploadImg();
        }
    }

    public void uploadImg() {
        OssManager.getInstance().upload(bankPath, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                LogUtils.e(TAG, "上传成功" +
                        "\nobjectKey:" + request.getObjectKey() +
                        "\nETag:" + result.getETag() +
                        "\nRequestId:" + result.getRequestId());
                bankUrl = OssManager.POINT + "/" + request.getObjectKey();
                isBankUploaded = true;
                upload();
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShort("图片上传失败，请检查手机网络是否畅通！");
                        getUC().getDismissLoadingDialogEvent().call();
                    }
                });
            }
        });
        OssManager.getInstance().upload(cardPath, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                LogUtils.e(TAG, "上传成功" +
                        "\nobjectKey:" + request.getObjectKey() +
                        "\nETag:" + result.getETag() +
                        "\nRequestId:" + result.getRequestId());
                cardUrl = OssManager.POINT + "/" + request.getObjectKey();
                isCardUploaded = true;
                upload();
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShort("图片上传失败，请检查手机网络是否畅通！");
                        getUC().getDismissLoadingDialogEvent().call();
                    }
                });
            }
        });
    }

    public void upload() {
        if (isCardUploaded && isBankUploaded) {
            model.upload(cardUrl, number.get(), bankUrl)
                    .observeOn(AndroidSchedulers.mainThread())
                    .doFinally(() -> {
                        getUC().getDismissLoadingDialogEvent().call();
                    })
                    .as(RxLife.as(owner))
                    .subscribe(been -> {
                        ToastUtils.showShort("上传成功！");
                    }, error -> {
                        ToastUtils.showShort(error.getMessage());
                    });
        }
    }

    private boolean isEmpty() {
        if (TextUtils.isEmpty(number.get())) {
            ToastUtils.showShort("请输入银行卡号！");
            return false;
        }
        if (TextUtils.isEmpty(bankPath)) {
            ToastUtils.showShort("请选择银行卡照片！");
            return false;
        }
        if (TextUtils.isEmpty(cardPath)) {
            ToastUtils.showShort("请选择身份证照片！");
            return false;
        }
        return true;
    }
}
